package com.wanmait.myhouse.webController;

import com.wanmait.myhouse.dao.HouseDAO;
import com.wanmait.myhouse.dao.UserDAO;
import com.wanmait.myhouse.vo.User;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("web")
public class WebInfoController {
    @GetMapping ("info")
    public String info(String userName, Model model ){
        UserDAO userDAO = new UserDAO();
        User users= userDAO.userByName(userName);
        model.addAttribute("InfoUser",users);
        return "/web/info";
    }
    @PostMapping("amend")
    public String amend(User user, HttpSession session,HttpServletRequest request, MultipartFile face){//修改数据库
        if (!face.isEmpty()){
            String filepath = request.getServletContext().getRealPath("/static/web/images");
            String originalFilename = face.getOriginalFilename();
            String fileext = FilenameUtils.getExtension(originalFilename);
            String filename = UUID.randomUUID().toString() + "." + fileext;
            try {
                user.setUserHead(filename);
                face.transferTo(new File(filepath+"/"+filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
            user.setUserHead(filename);
        }
        session.invalidate();
        UserDAO userDAO = new UserDAO();
        userDAO.updateFindUser(user);
        return "redirect:/web/login";
    }
}
